package data

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gomodule/redigo/redis"
	"github.com/xormplus/xorm"
	"os"
	"week13/configs"
	"week13/errors"
	"week13/log"
)
var MySQLConfig configs.MySQLConfig
var RedisConfig configs.RedisConfig
var Engine *xorm.Engine
func init() {
	err := initMySQLConfig()
	if err != nil {
		log.Fatal("mysql config, open file err: %s",err.Error())
	}
	err = initXORM(MySQLConfig)
	if err != nil {
		log.Fatal("init xorm  err: %s",err.Error())
	}
	err = initRedisConfig()
	if err != nil {
		log.Fatal("redis config, open file err: %s",err.Error())
	}
}
//初始DB配置
func initMySQLConfig() error{
	dir := "C:\\Users\\03\\Desktop\\training-camp\\week13\\configs\\json\\db.json"
	f, err := os.Open(dir)
	defer f.Close()
	if err != nil {
		return err
	}
	MySQLConfig = configs.LoadMySQLConfig(f)
	return nil
}
//初始化缓存设置
func initRedisConfig() error{
	dir := "C:\\Users\\03\\Desktop\\training-camp\\week13\\configs\\json\\redis.json"
	f, err := os.Open(dir)
	defer f.Close()
	if err != nil {
		return err
	}
	RedisConfig = configs.LoadRedisConfig(f)
	return nil
}

func initXORM(config configs.MySQLConfig) error {
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		MySQLConfig.UserName,
		MySQLConfig.Password,
		MySQLConfig.Host,
		MySQLConfig.Port,
		MySQLConfig.DbName)
	var err error
	Engine, err = xorm.NewEngine("mysql",dataSourceName)
	if err == nil {
		Engine.ShowSQL(true)
	}
	return err
}
func DBEngin() (*xorm.Engine,error){
	if Engine == nil {
		err := initMySQLConfig()
		if err != nil {
			log.Error("initMyConfig err:%s",err.Error())
			return nil,err
		}
		err = initXORM(MySQLConfig)
		if err != nil {
			log.Error("init xorm  err:%s",err.Error())
			return nil,err
		}
	}
	return Engine,nil
}

func Close(){
	Engine.Close()
	Engine = nil
}
//获取redis 客户端
func RedisClient() (redis.Conn,error){
	addr := fmt.Sprintf("%s:%s",RedisConfig.Host,RedisConfig.Port)
	c, err := redis.Dial("tcp", addr)
	if err != nil {
		return nil, errors.NewDialFail("connect redis fail")
	}
	return c,nil
}
